/** 状态配置 */
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    state: {
        user: {
            id: null,
            username: '',
            nickname: '',
            avatar: ''
        }
    },
    mutations: {
        LOGIN_SUCCESS: (state, loginUser) => {
            state.user.id = loginUser.id;
            state.user.username = loginUser.username;
            state.user.nickname = loginUser.nickname;
            state.user.avatar = loginUser.avatar;

            // 可以将其存储到localStorage
            let str = JSON.stringify(state.user);
            localStorage.setItem("user", str);
        },
        LOGOUT: state => {
            state.user.id = null;
            state.user.nickname = "";
            state.user.username = "";
            state.user.avatar = "";
            sessionStorage.removeItem("user");
        }
    },
    actions: {
        LoginSuccess: ({ commit }, loginUser) => {
            commit('LOGIN_SUCCESS', loginUser);
        },
        Logout: ({commit}) => {
            commit('LOGOUT');
        }
    },
    getters: {
        userId: state => state.user.id,
        username: state => state.user.username,
        nickname: state => state.user.nickname
    }
});

export default store;